import Vue from 'vue';
import VueRouter from 'vue-router';
// RouterTab 内置路由
import { RouterTabRoutes } from 'vue-router-tab';
import store from '@/store';

import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; //

NProgress.configure({ showSpinner: false }); // NProgress Configuration

Vue.use(VueRouter);

/**
 * static basic route
 */
const routes = [
  {
    path: '/',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ 'views/Login.vue'),
  },
  {
    path: '/logout',
    name: 'Logout',
    component: () => import(/* webpackChunkName: "logout" */ 'views/Logout.vue'),
  },
];

/**
 * 错误页面路由,要最后加载
 */
export const ErrorPageRoutes = [
  {
    path: '/404',
    component: () => import('views/404.vue'),
  },
  {
    path: '*',
    redirect: {
      path: '/404',
    },
  },
];

/**
 * 初始化 router
 */
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

// 切换角色时,覆盖路由方法
router.$addRoutes = (params) => {
  router.matcher = new VueRouter({
    // 重置路由规则
    routes,
  }).matcher;
  router.addRoutes(params); // 添加路由
};

router.onReady(() => {
  // 动态加载路由
  routeReadyHandler();
});

export const routeReadyHandler = () => {
  router.$addRoutes([...store.getters.$asyncRoute, ...ErrorPageRoutes]);
};
/**
 * 路由登录判断
 */
router.beforeEach(async (to, from, next) => {
  const { info } = store.getters.$userInfo;
  const token = store.getters.$token;
  NProgress.start();

  try {
    if (!info && token) {
      const userInfo = await Vue.prototype.$service.AuthInfo();

      store.dispatch('$setUserInfo', userInfo.user);
      store.dispatch('$setMenus', userInfo.menus);
      store.dispatch('$setPermission', userInfo.permissions);

      if (to.name === 'Login') {
        if (to.query.redirect && to.query.redirect.match(/settoken$/)) {
          window.location.href = `${to.query.redirect}?token=${encodeURIComponent(token)}`;
        } else {
          next({ path: '/d' });
        }
      }
    } else if (!token) {
      // 需要登录
      if (to.name !== 'Login') {
        next({ name: 'Login' });
      }
    }
  } catch {
    if (to.name !== 'Login') {
      next({ name: 'Login' });
    }
  }
  NProgress.done();
  next();
});

export default router;
